package com.atguigu.gmall.common.util;


import com.atguigu.gmall.common.constant.RedisConst;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.core.type.TypeReference;
import com.fasterxml.jackson.databind.ObjectMapper;
import lombok.extern.slf4j.Slf4j;

/**
 * ClassName: Jsons
 * Package: com.atguigu.gmall.common.util
 * Description:
 *
 * @Author ltystart
 * @Create 2025/8/24 15:52
 * @Version 1.0
 */
@Slf4j
public class Jsons {
    private static final ObjectMapper MAPPER = new ObjectMapper();

    public static String toStr(Object obj) {
        String json = null;
        try {
            json = MAPPER.writeValueAsString(obj);
        } catch (JsonProcessingException e) {
            log.error("对象{}，json转换异常：{}，", obj, e);
        }
        return json;
    }

    public static <T> T toObj(String jsonStr, TypeReference<T> tf) {
        if (RedisConst.TEMP_DATA.equals(jsonStr)) {
            return null;
        }
        T t = null;
        try {
            t = MAPPER.readValue(jsonStr, tf);
        } catch (JsonProcessingException e) {
            log.error("json字符串{}， 转对象异常：{}", jsonStr, e);
        }
        return t;
    }

    public static <T> T toObj(String jsonStr, Class<T> tf) {
        if (RedisConst.TEMP_DATA.equals(jsonStr)) {
            //如果redis缓存的是临时占位符，就创建一个空对象返回出去
//            T t = null;
//            try {
//                t = tf.newInstance();
//            } catch (InstantiationException e) {
//                e.printStackTrace();
//            } catch (IllegalAccessException e) {
//                e.printStackTrace();
//            }
//            return t;
            return null;
        }
        T t = null;
        try {
            t = MAPPER.readValue(jsonStr, tf);
        } catch (JsonProcessingException e) {
            log.error("json字符串{}， 转对象异常：{}", jsonStr, e);
        }
        return t;
    }
}
